package com.roadjava.rbac.service.impl;

import com.roadjava.rbac.bean.entity.Resource;
import com.roadjava.rbac.bean.req.resource.ResourcePageReq;
import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.mapper.ResourceMapper;
import com.roadjava.rbac.service.ResourceService;
import com.roadjava.rbac.config.RedisCache;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
/**
 * 资源服务实现类
 * @author 怨九己
 */
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl implements ResourceService {
    private final ResourceMapper resourceMapper;
    private final RedisCache redisCache;

    /**
     * 根据资源ID查询资源
     * @param resourceId 资源ID
     * @return 资源对象
     */
    @Override
    public Resource findById(Integer resourceId) {
        // 缓存键
        String cacheKey = "resource:" + resourceId;

        // 从 Redis 缓存中查询
        Resource cachedResource = redisCache.getCacheObject(cacheKey);
        if (cachedResource != null) {
            return cachedResource;
        }

        // 如果缓存中没有，从数据库中查询
        Resource resource = resourceMapper.findById(resourceId);

        // 如果数据库中有数据，存入缓存
        if (resource != null) {
            redisCache.setCacheObject(cacheKey, resource);
        }

        return resource;
    }

    /**
     * 保存资源
     *
     * @param resource 资源对象
     * @return 是否保存成功
     */
    @Override
    public Result<String> save(Resource resource) {
        resourceMapper.insert(resource);
        if (resource.getResourceId() != null) {
            // 删除单个资源的缓存
            String resourceCacheKey = "resource:" + resource.getResourceId();
            redisCache.deleteObject(resourceCacheKey);

            // 删除与资源名称和标签相关的缓存
            Collection<String> searchCacheKeys = redisCache.keys(
                    "resources:search:*:" +
                            resource.getResourceName() + ":*");
            searchCacheKeys.addAll(redisCache.keys(
                    "resources:search:*:" +
                            resource.getTag() + ":*"));
            redisCache.deleteObject(searchCacheKeys);

            return Result.buildSuccess("资源保存成功");
        } else {
            return Result.buildFailure("资源保存失败");
        }
    }
    /**
     * 删除资源
     * @param resourceId 资源ID
     */
    @Override
    public Result<String> delete(Integer resourceId) {
        Resource resource = resourceMapper.findById(resourceId);
        if (resource == null) {
            return Result.buildFailure("资源不存在，删除失败");
        }
        resourceMapper.delete(resourceId);

        // 删除单个资源的缓存
        String resourceCacheKey = "resource:" + resourceId;
        redisCache.deleteObject(resourceCacheKey);

        // 删除与资源名称和标签相关的缓存
        Collection<String> searchCacheKeys = redisCache.keys(
                "resources:search:*:" +
                        resource.getResourceName() + ":*");
        searchCacheKeys.addAll(redisCache.keys(
                "resources:search:*:" +
                        resource.getTag() + ":*"));
        redisCache.deleteObject(searchCacheKeys);

        return Result.buildSuccess("资源删除成功");
    }
    /**
     * 根据资源名称和标签搜索资源（支持分页）
     * @param resourceName 资源名称
     * @param tag 标签
     * @param pageReq 分页请求参数
     * @return 资源列表和总数
     */
//    @Override
//    public Result<List<Resource>> searchResourcesByName(
//            String resourceName,
//            String tag,
//            ResourcePageReq pageReq) {
//        // 缓存键
//        String cacheKey =
//                "resources:search:" +
//                        resourceName + ":" +
//                        tag + ":" +
//                        pageReq.getPageNum() + ":" +
//                        pageReq.getPageSize();
//
//        // 从 Redis 缓存中查询
//        Result<List<Resource>> cachedResult =
//                redisCache.getCacheObject(cacheKey);
//        if (cachedResult != null) {
//            return cachedResult;
//        }
//
//        // 如果缓存中没有，从数据库中查询
//        int offset = (pageReq.getPageNum() - 1) * pageReq.getPageSize();
//        List<Resource> resources =
//                resourceMapper.searchResourcesByName(
//                        resourceName,
//                        tag,
//                        offset,
//                        pageReq.getPageSize());
//        Long total =
//                resourceMapper.countSearchResourcesByName(resourceName, tag);
//        Result<List<Resource>> result = Result.buildSuccess(resources, total);
//
//        // 如果数据库中有数据，存入缓存
//        if (resources != null && !resources.isEmpty()) {
//            redisCache.setCacheObject(cacheKey, result);
//        }
//
//        return result;
//    }
    /**
     * 根据资源名称和标签搜索资源（支持分页）
     * @param resourceName 资源名称
     * @param tag 标签
     * @param pageReq 分页请求参数
     * @return 资源列表和总数
     */
    @Override
    public Result<List<Resource>> searchResourcesByName(
            String resourceName,
            String tag,
            ResourcePageReq pageReq) {
        // 缓存键
        String cacheKey =
                "resources:search:" +
                resourceName + ":" +
                tag + ":" +
                pageReq.getPageNum() + ":" +
                pageReq.getPageSize();

        // 从 Redis 缓存中查询
        Result<List<Resource>> cachedResult =
                redisCache.getCacheObject(cacheKey);
        if (cachedResult != null) {
            return cachedResult;
        }

        // 如果缓存中没有，从数据库中查询
        int offset = (pageReq.getPageNum() - 1) * pageReq.getPageSize();
        List<Resource> resources =
                resourceMapper.searchResourcesByName(
                        resourceName,
                        tag,
                        offset,
                        pageReq.getPageSize());
        Long total =
                resourceMapper.countSearchResourcesByName(resourceName, tag);
        Result<List<Resource>> result = Result.buildSuccess(resources, total);

        // 如果数据库中有数据，存入缓存
        if (resources != null && !resources.isEmpty()) {
            redisCache.setCacheObject(cacheKey, result);
        }

        return result;
    }

    /**
     * 更新资源（只允许修改 resourceType, resourceDescription, 和 tag）
     * @param resourceId 资源ID
     * @param resourceUpdate 资源更新对象
     * @return 更新后的资源对象
     */
    @Override
    public Resource updateResource(
            Integer resourceId,
            Resource resourceUpdate) {
        Resource existingResource = resourceMapper.findById(resourceId);
        if (existingResource != null) {
            // 更新资源属性
            existingResource.setResourceType(
                    resourceUpdate.getResourceType());
            existingResource.setResourceDescription(
                    resourceUpdate.getResourceDescription());
            existingResource.setTag(
                    resourceUpdate.getTag());
            resourceMapper.updateResource(existingResource);

            // 删除单个资源的缓存
            String resourceCacheKey = "resource:" + resourceId;
            redisCache.deleteObject(resourceCacheKey);

            // 删除与资源名称和标签相关的缓存
            Collection<String> searchCacheKeys = redisCache.keys(
                    "resources:search:*:" +
                            existingResource.getResourceName() + ":*");
            searchCacheKeys.addAll(redisCache.keys(
                    "resources:search:*:" +
                            existingResource.getTag() + ":*"));
            redisCache.deleteObject(searchCacheKeys);
        }
        return existingResource;
    }

    /**
     * 分页查询资源
     * @param pageReq 分页请求参数
     * @return 资源列表和总数
     */
    @Override
    public Result<List<Resource>> queryPage(ResourcePageReq pageReq) {
        int offset = (pageReq.getPageNum() - 1) * pageReq.getPageSize();
        List<Resource> resources = resourceMapper.queryPage(
                offset,
                pageReq.getPageSize());
        Long total = resourceMapper.countTotalResources();
        return Result.buildSuccess(resources, total);
    }
}